﻿using System;
using System.IO;
using System.Text;

/* jsmin.c
   2007-05-22

Copyright (c) 2002 Douglas Crockford  (www.crockford.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

namespace CMSN.Software.Tutorials.HowToCompressCssAndJs
{
    public class JavaScriptMinifier
    {
        private const int EndOfFile = -1;

        StreamReader streamReader;
        StreamWriter streamWriter;
        int firstCharacter;
        int nextCharacter;
        int theLookahead = EndOfFile;

        public string MinifyJavaScript(string src)
        {
            MemoryStream srcStream = new MemoryStream(Encoding.Unicode.GetBytes(src));
            MemoryStream tgStream = new MemoryStream(8092);

            using (streamReader = new StreamReader(srcStream, Encoding.Unicode))
            {
                using (streamWriter = new StreamWriter(tgStream, Encoding.Unicode))
                {
                    JavaScriptMinify();
                }
            }

            return Encoding.Unicode.GetString(tgStream.ToArray());
        }

        /// <summary>
        /// Copy the input to the output, deleting the characters which are
        /// insignificant to JavaScript. Comments will be removed. Tabs will be
        /// replaced with spaces. Carriage returns will be replaced with linefeeds.
        /// Most spaces and linefeeds will be removed.
        /// </summary>
        private void JavaScriptMinify()
        {
            firstCharacter = '\n';
            JavaScriptMinifyAction(3);
            while (firstCharacter != EndOfFile)
            {
                switch (firstCharacter)
                {
                    case ' ':
                        {
                            if (isAlphanum(nextCharacter))
                            {
                                JavaScriptMinifyAction(1);
                            }
                            else
                            {
                                JavaScriptMinifyAction(2);
                            }

                            break;
                        }
                    case '\n':
                        {
                            switch (nextCharacter)
                            {
                                case '{':
                                case '[':
                                case '(':
                                case '+':
                                case '-':
                                    {
                                        JavaScriptMinifyAction(1);
                                        break;
                                    }
                                case ' ':
                                    {
                                        JavaScriptMinifyAction(3);
                                        break;
                                    }
                                default:
                                    {
                                        if (isAlphanum(nextCharacter))
                                        {
                                            JavaScriptMinifyAction(1);
                                        }
                                        else
                                        {
                                            JavaScriptMinifyAction(2);
                                        }
                                        break;
                                    }
                            }
                            break;
                        }
                    default:
                        {
                            switch (nextCharacter)
                            {
                                case ' ':
                                    {
                                        if (isAlphanum(firstCharacter))
                                        {
                                            JavaScriptMinifyAction(1);
                                            break;
                                        }
                                        JavaScriptMinifyAction(3);
                                        break;
                                    }
                                case '\n':
                                    {
                                        switch (firstCharacter)
                                        {
                                            case '}':
                                            case ']':
                                            case ')':
                                            case '+':
                                            case '-':
                                            case '"':
                                            case '\'':
                                                {
                                                    JavaScriptMinifyAction(1);
                                                    break;
                                                }
                                            default:
                                                {
                                                    if (isAlphanum(firstCharacter))
                                                    {
                                                        JavaScriptMinifyAction(1);
                                                    }
                                                    else
                                                    {
                                                        JavaScriptMinifyAction(3);
                                                    }
                                                    break;
                                                }
                                        }
                                        break;
                                    }
                                default:
                                    {
                                        JavaScriptMinifyAction(1);
                                        break;
                                    }
                            }
                            break;
                        }
                }
            }
        }

        /// <summary>
        /// JavaScript minify action.
        /// </summary>
        /// <param name="actionNumber">action number</param>
        private void JavaScriptMinifyAction(int actionNumber)
        {
            if (actionNumber <= 1)
            {
                put(firstCharacter);
            }
            if (actionNumber <= 2)
            {
                firstCharacter = nextCharacter;
                if (firstCharacter == '\'' || firstCharacter == '"')
                {
                    for (; ; )
                    {
                        put(firstCharacter);
                        firstCharacter = get();
                        if (firstCharacter == nextCharacter)
                        {
                            break;
                        }
                        if (firstCharacter <= '\n')
                        {
                            throw new FormatException(string.Format("Error: JSMIN unterminated string literal: {0}\n", firstCharacter));
                        }
                        if (firstCharacter == '\\')
                        {
                            put(firstCharacter);
                            firstCharacter = get();
                        }
                    }
                }
            }
            if (actionNumber <= 3)
            {
                nextCharacter = NextCharacter();
                if (nextCharacter == '/' && (firstCharacter == '(' || firstCharacter == ',' || firstCharacter == '=' ||
                                    firstCharacter == '[' || firstCharacter == '!' || firstCharacter == ':' ||
                                    firstCharacter == '&' || firstCharacter == '|' || firstCharacter == '?' ||
                                    firstCharacter == '{' || firstCharacter == '}' || firstCharacter == ';' ||
                                    firstCharacter == '\n'))
                {
                    put(firstCharacter);
                    put(nextCharacter);
                    for (; ; )
                    {
                        firstCharacter = get();
                        if (firstCharacter == '/')
                        {
                            break;
                        }
                        else if (firstCharacter == '\\')
                        {
                            put(firstCharacter);
                            firstCharacter = get();
                        }
                        else if (firstCharacter <= '\n')
                        {
                            throw new Exception(string.Format("Error: JSMIN unterminated Regular Expression literal : {0}.\n", firstCharacter));
                        }
                        put(firstCharacter);
                    }
                    nextCharacter = NextCharacter();
                }
            }
        }

        /* next -- get the next character, excluding comments. peek() is used to see
                if a '/' is followed by a '/' or '*'.
        */

        private int NextCharacter()
        {
            int c = get();
            if (c == '/')
            {
                switch (peek())
                {
                    case '/':
                        {
                            for (; ; )
                            {
                                c = get();
                                if (c <= '\n')
                                {
                                    return c;
                                }
                            }
                        }
                    case '*':
                        {
                            get();
                            for (; ; )
                            {
                                switch (get())
                                {
                                    case '*':
                                        {
                                            if (peek() == '/')
                                            {
                                                get();
                                                return ' ';
                                            }
                                            break;
                                        }
                                    case EndOfFile:
                                        {
                                            throw new Exception("Error: JSMIN Unterminated comment.\n");
                                        }
                                }
                            }
                        }
                    default:
                        {
                            return c;
                        }
                }
            }
            return c;
        }

        /* peek -- get the next character without getting it.
        */

        private int peek()
        {
            theLookahead = get();
            return theLookahead;
        }

        /* get -- return the next character from stdin. Watch out for look ahead. If
                the character is a control character, translate it to a space or
                linefeed.
        */

        private int get()
        {
            int c = theLookahead;
            theLookahead = EndOfFile;
            if (c == EndOfFile)
            {
                c = streamReader.Read();
            }
            if (c >= ' ' || c == '\n' || c == EndOfFile)
            {
                return c;
            }
            if (c == '\r')
            {
                return '\n';
            }
            return ' ';
        }

        private void put(int c)
        {
            streamWriter.Write((char)c);
        }

        /* isAlphanum -- return true if the character is a letter, digit, underscore,
                dollar sign, or non-ASCII character.
        */

        private bool isAlphanum(int c)
        {
            return ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
                (c >= 'A' && c <= 'Z') || c == '_' || c == '$' || c == '\\' ||
                c > 126);
        }
    }
}